import getTempId from '@/utils/userTempId'
import { SET_USER_TOKEN_STORE, SET_USER_INFO_STORE, DEL_USER_TOKEN_STORE } from '../constant-type'
import { reqUserLogin, getUserInfo, reqLogOut } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'
const state = {
    userTempId: getTempId(),
    token: getToken() || '',
    userInfo: {}
}
const mutations = {
    [SET_USER_TOKEN_STORE](state, payload) {
        state.token = payload.token
        setToken(payload.token)
    },
    [SET_USER_INFO_STORE](state, payload) {
        state.userInfo = payload
    },
    [DEL_USER_TOKEN_STORE](state) {
        state.userInfo = {}
        state.token = ''
    },
}
const actions = {
    async setTokenAction({ commit }, payload) {
        try {
            let re = await reqUserLogin(payload)
            commit(SET_USER_TOKEN_STORE, re)
        } catch (error) {
            // 同样,错误被内部处理,不会被外部捕获
            return Promise.reject(error)
        }
    },
    async setUserInfo({ commit }) {
        try {
            let re = await getUserInfo()
            commit(SET_USER_INFO_STORE, re)
        } catch (error) {
            //如果数据过期,就删除所有的token,嗲用退出登录函数,使其重新登录,否则本地的过期token会一直存储并无法通过后端的鉴权
            // 导致bug
            return Promise.reject(error)
        }
    },
    async removeToken_Local({ commit }) {
        // 发送请求使得token失效
        await reqLogOut()
        // 删除本地local中的token
        removeToken()
        // 删除vuex中的token和userInfo
        commit(DEL_USER_TOKEN_STORE)
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}